<?php


namespace App\Http\Api\Controllers;


use App\Http\Api\Util;
use App\Library\JsonData;
use App\Models\CoUser;
use EasyWeChat\Factory;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Ramsey\Uuid\Uuid;

class LoginController extends Controller
{
    public function __construct()
    {
        // 调用父类前置方法
        parent::__construct();
    }

    public function login(Request $request){
        $config = config("wechat.mini_program.default");
        $app = Factory::miniProgram($config);
        $credentials      = $request->all();
        $validator = Validator::make($credentials, [
            'code' => 'required',
        ]);
        if ($validator->fails()) {
            return JsonData::error('参数错误','',500);
        }
        try {
            $res = $app->auth->session($request->input("code", ''));
            if (isset($res['openid'])) {
                //微信登录成功 获取openid
                $openid = $res['openid'];
                $token = Uuid::uuid1();
                DB::beginTransaction();
                //是否首次，首次则注册
                $user = CoUser::where("openid", $openid)->first();
                if (!$user) {
                    $register = new CoUser();
                    $register->openid = $res['openid'];
                    /*$register->nickname = "";//微信昵称*/
                    /*$register->avatar = "asdasdasdasa";//头像用微信头像？*/
                    $register->gender = 1;
                    $register->regist_date = date("Y-m-d h:i:s");//注册时间
                    $register->api_token = $token;
                    /*start事务*/

//                        DB::beginTransaction();
                        $save = $register->save();
                        if (!$save) {//注册失败
                            DB::rollBack();
                            return JsonData::error("注册失败！",'',500);
                        }

                    /*end事务*/
                }else{
                    //更新时间
                    $user->api_token = $token;
                    $user->login_time = date("Y-m-d h:i:s");
                    $user->save();
                }
                DB::commit();
                //登录信息
                $user = CoUser::where("openid", $openid)
                    ->select("id", "openid", "nickname", "gender", "avatar", "is_type",'is_shen','school_id','api_token as token','type')
                    ->first();
                if($user->type ==1){
                    return JsonData::success("登录成功",$user, 200);
                }else{
                    return JsonData::error("用户被禁止登录",'',500);
                }
            } else {
                return JsonData::error("授权登录失败",'',500);
            }
        } catch (\Exception $e) {
            //配置错误时排除异常
            return JsonData::error($e->getMessage(),'',500 );
        }
    }
}
